package com.jsz.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.jsz.pojo.Permission;
import com.jsz.pojo.Role;
import com.jsz.pojo.User;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * security权限框架.用户认证与授权
 */
@Component("springSecurityUserService")
public class SpringSecurityUserService implements UserDetailsService {
    //使用dubbo通过网络远程调用服务提供方获取数据库中的用户信息
    @Reference
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //根据用户名去查询数据库
        User user = userService.findByUsername(username);
        //调试
        //System.out.println("loadUserByUsername中从数据库查询到的"+user);
        if (user == null) {
            //用户名不存在,retrun null 终止代码
            return null;
        }
        /*根据user的id去查询 t_role表（角色表）
          根据role的id去查询 t_permission表（权限表）
          定义一个List集合用来封装数据*/
        List<GrantedAuthority> list = new ArrayList<>();
        //获取用户对应的角色信息
        Set<Role> roles = user.getRoles();
        //获取每个角色信息,并动态为用户授予对应的角色信息
        for (Role role : roles) {
            //调试
            System.out.println("role 信息："+role.getKeyword());
            //将查询到的角色信息代入指定的list集合中,由框架操作
            list.add(new SimpleGrantedAuthority(role.getKeyword()));
            //获取每个觉得对应的权限
            Set<Permission> permissions = role.getPermissions();
            for (Permission permission : permissions) {
                //获取每一个角色对应的权限,为用户授权
                //System.out.println("permission 信息："+permission.getKeyword());
                list.add(new SimpleGrantedAuthority(permission.getKeyword()));
            }
        }
        //经过上面2次的循环,就把用户对应的角色,以及角色对应的权限都给添加到了上面的list集合中去了
        //在把list带给security框架进行比对和授权
        org.springframework.security.core.userdetails.User securityUser
                = new org.springframework.security.core.userdetails.User(username, user.getPassword(), list);

        //System.out.println("返回给security框架的: "+securityUser+"对象");
        return securityUser;
    }
}



